from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
from fastapi import status
from .config import app, dblock
from dataclasses import asdict

router = APIRouter(prefix="/api/class", tags=["class"])

@router.get("/list")
def list_class():
    with dblock() as db:
        db.execute("SELECT sn, name, course_sn, schedule FROM class ORDER BY sn")
        data = [asdict(row) for row in db]
    return data

@router.post("/new")
async def new_class(request: Request):
    data = await request.json()
    name = data.get('name')
    course_sn = data.get('course_sn')
    schedule = data.get('schedule')
    with dblock() as db:
        db.execute(
            """
            INSERT INTO class (name, course_sn, schedule)
            VALUES (%(name)s, %(course_sn)s, %(schedule)s)
            RETURNING sn
            """,
            {"name": name, "course_sn": course_sn, "schedule": schedule}
        )
        row = db.fetchone()
    return JSONResponse(content={"msg": "新建班次成功", "sn": row.sn}, status_code=status.HTTP_201_CREATED)
# 其他增删改查API可后续补充